###############################################################################
# Top contributors (to current version):
#   Gereon Kremer
#
# This file is part of the cvc5 project.
#
# Copyright (c) 2009-2024 by the authors listed in the file AUTHORS
# in the top-level source directory and their institutional affiliations.
# All rights reserved.  See the file COPYING in the top-level source
# directory for licensing information.
# #############################################################################
#
# Build system configuration for java API documentation.
#

add_custom_target(docs-java)

if(BUILD_BINDINGS_JAVA)
  find_package(Java REQUIRED)

  # put generated doc in a place where sphinx can easily copy from
  set(JAVADOC_OUTPUT_DIR ${CMAKE_CURRENT_BINARY_DIR}/build/api/java)
  # used to trigger the rebuild
  set(JAVADOC_INDEX_FILE ${JAVADOC_OUTPUT_DIR}/index.html)
  # HTML added to javadoc to include Mathjax
  # This is fragile with respect to escapes:
  #   - The LaTeX sequence '$#1$' must be written as '\$$#1$$'.
  #   - Whitespaces in some places must be omitted, otherwise
  #     they become ';'.
  #   - To make LaTeX commands work they need '\\\\'.
  set(JAVADOC_MATHJAX [=["
    <script>
    window.MathJax = {
      'loader': {
        'load': ['[tex]/ams','[tex]/bussproofs'],
      },
      'tex': {
        'packages': {
          '[+]': ['ams','bussproofs'],
        },
        'macros': {
          'xor': '\\\\mathbin{xor}',
          'ite': ['#1~\\\\mathbin{?}~#2~\\\\mathbin{:}~#3',3],
          'inferrule': ['\\\\begin{prooftree}\\\\AxiomC{\$$#1$$}\\\\UnaryInfC{\$$#2$$}\\\\end{prooftree}',2],
          'inferruleSC': ['\\\\begin{prooftree}\\\\AxiomC{\$$#1$$}\\\\RightLabel{~#3}\\\\UnaryInfC{\$$#2$$}\\\\end{prooftree}',3],
        }
      }
    }
    </script>
    <script type='text/javascript' id='MathJax-script' async src='https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'>
    </script>
  "]=])
  string(REPLACE "\n" " " JAVADOC_MATHJAX ${JAVADOC_MATHJAX})
  string(REPLACE " " ";" JAVADOC_MATHJAX ${JAVADOC_MATHJAX})

  get_target_property(CVC5_JAR_FILE cvc5jar JAR_FILE)
  add_custom_command(
    OUTPUT ${JAVADOC_INDEX_FILE}
    COMMAND
      ${Java_JAVADOC_EXECUTABLE} io.github.cvc5
      -sourcepath ${CMAKE_SOURCE_DIR}/src/api/java/:${CMAKE_BINARY_DIR}/src/api/java/
      -d ${JAVADOC_OUTPUT_DIR}
      -cp ${CVC5_JAR_FILE}
      -tag "api.note:a:Note:"
      --allow-script-in-comments
      -header ${JAVADOC_MATHJAX}
      -notimestamp
      -subpackages io.github.cvc5.modes
    COMMAND find ${JAVADOC_OUTPUT_DIR} -type f -exec sed -i'orig' 's/<!-- Generated by javadoc [^>]* -->//' {} "\;"
    COMMAND find ${SPHINX_GH_OUTPUT_DIR} -name '*orig' -delete
    DEPENDS cvc5jar ${CVC5_JAR_FILE}
    COMMENT "Generating javadocs"
  )

  add_custom_target(docs-java-javadoc DEPENDS ${JAVADOC_INDEX_FILE})
  add_dependencies(docs-java docs-java-javadoc)
endif()

